using AutoMapper;
using BaseData.ReadApi.Appcontext.Command.Ewe_Files;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.ReadApi.Appcontext.CommandHandler.Ewe_Files
{
    /// <summary>
    /// 母羊档案分页查询命令处理器
    /// </summary>
    public class GetEweFilesPagedCommandHandler : IRequestHandler<GetEweFilesPagedCommand, ApiResult<ApiPaging<EweFile>>>
    {
        private readonly IBaseRepository<EweFile> _eweRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetEweFilesPagedCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="eweRepository">母羊档案仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetEweFilesPagedCommandHandler(
            IBaseRepository<EweFile> eweRepository,
            IMapper mapper,
            ILogger<GetEweFilesPagedCommandHandler> logger)
        {
            _eweRepository = eweRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理母羊档案分页查询命令
        /// </summary>
        /// <param name="request">母羊档案分页查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页查询结果</returns>
        public async Task<ApiResult<ApiPaging<EweFile>>> Handle(GetEweFilesPagedCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("母羊档案分页查询请求参数为空");
                    return new ApiResult<ApiPaging<EweFile>>
                {
                    Code = ApiEnum.查询失败,
                    Message = "请求参数不能为空",
                    data = default
                };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"母羊档案分页查询数据验证失败: {errorMessage}");
                    return new ApiResult<ApiPaging<EweFile>>
                    {
                        Code = ApiEnum.查询失败,
                        Message = errorMessage,
                        data = default
                    };
                }

                // 获取所有未被删除的母羊档案
                var query = _eweRepository.GetAll()
                    .Where(e => !e.IsDeleted);

                // 应用搜索条件
                if (!string.IsNullOrEmpty(request.EarSignal))
                {
                    query = query.Where(e => e.EarSignal.Contains(request.EarSignal));
                }

                if (!string.IsNullOrEmpty(request.ElectronicEarTag))
                {
                    query = query.Where(e => e.ElectronicEarTag.Contains(request.ElectronicEarTag));
                }

                if (request.Variety.HasValue)
                {
                    query = query.Where(e => e.Variety == request.Variety.Value);
                }

                if (request.GeneLevel.HasValue)
                {
                    query = query.Where(e => e.GeneRank == request.GeneLevel.Value);
                }

                // 计算总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 计算总页数
                var totalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize);

                // 获取分页数据
                var pagedData = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 构建分页结果
                var pagingResult = new ApiPaging<EweFile>
                {
                    totalPage = totalPages,
                    totalCount = totalCount,
                    data = pagedData
                };

                _logger.LogInformation($"母羊档案分页查询成功，页码: {request.PageIndex}, 每页条数: {request.PageSize}, 总页数: {totalPages}");
                return new ApiResult<ApiPaging<EweFile>>
                {
                    Code = ApiEnum.查询成功,
                    Message = "母羊档案分页查询成功",
                    data = pagingResult
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"母羊档案分页查询时发生系统异常: {ex.Message}");
                return new ApiResult<ApiPaging<EweFile>>
                {
                    Code = ApiEnum.查询失败,
                    Message = "系统异常，请联系管理员",
                    data = default
                };
            }
        }
    }
}